package model

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"go-base/hs-gin/conf"
	"github.com/spf13/viper"
)

var MDB *gorm.DB
var MDB2 *gorm.DB
var MDB3 *gorm.DB
var MDB4 *gorm.DB

func NewMysqlOrm() {
	str := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s",
		conf.Configer.DbConf.User, conf.Configer.DbConf.Password, conf.Configer.DbConf.Host, conf.Configer.DbConf.Port, conf.Configer.DbConf.Database, conf.Configer.DbConf.Charset, conf.Configer.DbConf.TimeZone)
	fmt.Println("mysql:", str)
	//log.Info("mysql conn db_out source", serviceDbOutMysql.Source(), serviceDbOutMysql.GetShowLog())
	var err error
	MDB, err = gorm.Open("mysql", str)
	if err != nil {
		panic(err.Error())
	}

	MDB.LogMode(conf.Configer.DbConf.ShowLog)
	MDB.DB().SetMaxIdleConns(conf.Configer.DbConf.MaxIdleConns)
	MDB.DB().SetMaxOpenConns(conf.Configer.DbConf.MaxOpenConns)

	if len(viper.GetString("db2.driverName")) > 0 {
		str2 := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s",
			viper.GetString("db2.user"), viper.GetString("db2.password"), viper.GetString("db2.host"), viper.GetString("db2.port"), viper.GetString("db2.database"), viper.GetString("db2.charset"), viper.GetString("db2.timeZone"))
		fmt.Println("mysql2:", str2)

		var err2 error
		MDB2, err2 = gorm.Open("mysql", str2)
		if err2 != nil {
			panic(err2.Error())
		}

		MDB2.LogMode(viper.GetBool("db2.showLog"))
		MDB2.DB().SetMaxIdleConns(viper.GetInt("db2.maxIdleConn"))
		MDB2.DB().SetMaxOpenConns(viper.GetInt("db2.maxOpenConn"))
	}

	if len(viper.GetString("db3.driverName")) > 0 {
		str3 := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s",
			viper.GetString("db3.user"), viper.GetString("db3.password"), viper.GetString("db3.host"), viper.GetString("db3.port"), viper.GetString("db3.database"), viper.GetString("db3.charset"), viper.GetString("db3.timeZone"))
		fmt.Println("mysql3:", str3)

		var err3 error
		MDB3, err3 = gorm.Open("mysql", str3)
		if err3 != nil {
			panic(err3.Error())
		}

		MDB3.LogMode(viper.GetBool("db3.showLog"))
		MDB3.DB().SetMaxIdleConns(viper.GetInt("db3.maxIdleConn"))
		MDB3.DB().SetMaxOpenConns(viper.GetInt("db3.maxOpenConn"))
	}

	if len(viper.GetString("db4.driverName")) > 0 {
		str4 := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s",
			viper.GetString("db4.user"), viper.GetString("db4.password"), viper.GetString("db4.host"), viper.GetString("db4.port"), viper.GetString("db4.database"), viper.GetString("db4.charset"), viper.GetString("db4.timeZone"))
		fmt.Println("mysql4:", str4)

		var err4 error
		MDB4, err4 = gorm.Open("mysql", str4)
		if err4 != nil {
			panic(err4.Error())
		}

		MDB4.LogMode(viper.GetBool("db4.showLog"))
		MDB4.DB().SetMaxIdleConns(viper.GetInt("db4.maxIdleConn"))
		MDB4.DB().SetMaxOpenConns(viper.GetInt("db4.maxOpenConn"))
	}
}
